"use strict";
/* Controllers */
app.controller("smartDqAddController", ['$scope', '$location', '$rootScope', '$routeParams', 'smartDqAddService', function ($scope, $location, $rootScope, $routeParams, smartDqAddService) {

    var vm = $scope.vm = {};
    vm.p = {};
    vm.result = {};

    vm.p.type = $routeParams.type;
    if (vm.p.type == 'id') {
        vm.p.tableId = $routeParams.id;
    } else {
        vm.p.tableName = $routeParams.id;
    }

    var errorFn = function (result) {
        alert(result);
    };

    $scope.getLogicTable = function () {
        var vm = $scope.vm;
        vm.result.ms = "...";
        // 请求参数
        var params = {
            tableId: vm.p.tableId,
            tableName: vm.p.tableName
        };

        // 结果处理
        var procFn = function (response) {
            if ("000" !== response.code) {
                alert(response.message);
                return;
            }
            vm.result.ms = response.ms;
            var data = response.data;
            if (data == null) return;
            vm.result.data = data;

            vm.p = data;
//            var columnListFmt = function (val) {
//                var ret = [];
//                var list = val.split(',');
//                for (var i in list) {
//                    var it = list[i].split('^');
//                    ret.push({'columnId':it[0],'columnName':it[1],'columnNameCn':it[2],'columnType':it[3],'columnCommon':it[4]});
//                }
//                return ret;
//            };
//            var tableCreateFmt = function (tableName, tableNameCn, tableComment, columnList) {
//                var ret = 'create table ' + tableName + ' ( ';
//                var columns = columnListFmt(columnList);
//                for (var i in columns) {
//                    var col = columns[i];
//                    if(i>0) {
//                        ret += ',';
//                    }
//                    var row = col.columnName + ' ' + col.columnType + " COMMENT '" + col.columnNameCn + ',' + col.columnCommon +"'"
//                    ret += row;
//                }
//                ret += ') '
//                ret += ("COMMENT '" + tableNameCn + ',' + tableComment + "'")
//                return ret;
//            };
//            vm.p.tableCreate = tableCreateFmt(data.tableName, data.tableNameCn, data.tableComment,data.columnList);
        };
        return smartDqAddService.getLogicTable(params, procFn, errorFn);
    };

    var commentParser = function(comment) {
        var str = comment.trim();

        // 去掉第一个和最后一个字符
        var str2 = str.substring(1,str.length-1);
        var items = str2.split(/,|，|。/);

        return {'cname': items[0], 'comment': items[1]};
    }

    var nameParser = function(name) {
        var str = name.trim();
        // 去掉第一个和最后一个字符
        var str2 = str.substring(1,str.length-1);
        return str2;
    }

    var sqlParser = function(val) {
        var str = val.toLowerCase();
        var start=0, end=0;
        // table name
        start = str.indexOf("create table");
        var colStart = str.indexOf("(", start);
        var tableName = str.slice(start+12,colStart);

        // table comment
        var colEnd = str.indexOf(") comment", colStart);
        var tableComment = str.substr(colEnd+9);
        var tableCommentObj = commentParser(tableComment);

        // columns
        var columns = str.slice(colStart+1, colEnd);

        var arr = [];
        while(1) {
            columns = columns.trim();
            if(columns.length==0) {
                break;
            }
            start = 0;
            end = columns.indexOf(' ',start);
            if (end<=start) {
                break;
            }
            var name = columns.slice(start, end);

            start = end + 1;
            end = columns.indexOf(' ', start);
            var type = columns.slice(start, end);

            start = end + 1;
            end = columns.indexOf("comment", start);// length(comment ")=9
            start = end + 8;
            end = columns.indexOf(columns.charAt(start), start+1);
            var comment = columns.slice(start, end+1);
            columns = columns.substr(end+2);// length(',)=2

            var obj = commentParser(comment);
            obj.column=name;
            obj.type=type;

            arr.push(obj);
        }
        var ret = {'tableName':tableName, 'tableNameCn':tableCommentObj.cname, 'tableComment':tableCommentObj.comment, 'columnList': arr};


        return ret;
    }

    var updateParam = function(ret) {
        var vm = $scope.vm;

        vm.p.tableName = nameParser(ret.tableName);
        vm.p.tableNameCn = ret.tableNameCn.trim();

        if(typeof(ret.tableComment)=='undefined') {
            ret.tableComment = vm.p.tableNameCn;
        }
        vm.p.tableComment= ret.tableComment.trim();

        var columnListFmt = function(columns) {
            var arr = [];
            for(var i in columns) {
                var r = columns[i];
                var col = nameParser(r.column);
                if(typeof(r.comment)=='undefined') {
                    r.comment = '-';
                }
                var str = [col,r.cname,r.type,r.comment].join('^')
                arr.push(str);
            }
            return arr.join(',');
        };
        vm.p.columnList = columnListFmt(ret.columnList);
    }

    $scope.checkCreateSQL = function() {
        var vm = $scope.vm;
        var ret = sqlParser(vm.p.tableCreate);
        updateParam(ret);

        var msg = ('success.'
            + vm.p.tableName + '('+vm.p.tableNameCn+')'
            + vm.p.tableComment
            +'['+ vm.p.columnList+']');
        alert(msg);
        console.log(msg);
    };
    $scope.checkQuerySQL = function() {
        var vm = $scope.vm;
        alert('success');
    };
    $scope.setLogicTable = function () {
        var vm = $scope.vm;
//        var columnListFmt = function(createSql) {
//            return '';
//        }
//        vm.p.columnList = columnListFmt(vm.p.tableCreate);
        var ret = sqlParser(vm.p.tableCreate);
        updateParam(ret);

        var params = vm.p;
        var procFn = function (response) {
            if (response.success && response.data) {
                alert("执行成功！");
            } else {
                alert(response.message);
            }
        };
        return smartDqAddService.setLogicTable(params, procFn, errorFn);
    };

    $scope.initializeController = function () {
        vm.result.ms = '';

        var $resultTable = $('#list_table');
        $resultTable.bootstrapTable({
            pageItem: [30, 50, 100, 300, 500, 1000], pageSize: 30
        });
        if(vm.p.tableId!='0') {
            $scope.getLogicTable();
        }
    };

    $scope.initializeController();

}]);


/* Services */
app.service('smartDqAddService', ['ajaxService', function (ajaxService) {

    this.getLogicTable = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/smartdq/getLogicTable.do", successFunction, errorFunction);
    };

    this.setLogicTable = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/smartdq/setLogicTable.do", successFunction, errorFunction);
    };


}]);


